package com.bigknow.appstore.server.rpc;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.HashMap;
import java.util.Map;

import com.bigknow.appstore.common.rpc.MuxAction;

public class SSLServer {

	private int port;

	private EventLoopGroup acceptGroup;

	private EventLoopGroup processGroup;

	private Map<MuxAction, MuxActionHandler> handlers = new HashMap<MuxAction, MuxActionHandler>();

	public SSLServer(int port, int acceptThread, int processThread) {
		this.port = port;
		this.acceptGroup = new NioEventLoopGroup(acceptThread);
		this.processGroup = new NioEventLoopGroup(processThread);
		initHandler();
	}

	private void initHandler() {
		handlers.put(MuxAction.MAIN, new RPCServer());
	}

	public void start() {
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(acceptGroup, processGroup).channel(NioServerSocketChannel.class)
					.handler(new LoggingHandler(LogLevel.INFO)).childHandler(new SSLServerInitializer(this));

			b.bind(port).sync().channel();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void stop() {
		acceptGroup.shutdownGracefully();
		processGroup.shutdownGracefully();
	}

	public MuxActionHandler getHandler(MuxAction action) {
		return handlers.get(action);
	}
}
